package com.kevin.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * kevin<br/>
 * 2020/11/12 10:13<br/>
 */
public class BeanCopyUtil {

    private static final Logger logger = LoggerFactory.getLogger(BeanCopyUtil.class);

    private static final Map<String, BeanCopier> BEAN_COPIER_CACHE = new ConcurrentHashMap<>();

    public static void copy(Object source, Object target) {
        BeanCopier copier = getBeanCopier(source.getClass(), target.getClass());
        copier.copy(source, target, null);
    }

    public static <T> T copy(Object source, Class<T> targetClazz) {
        T target = null;
        try {
            target = targetClazz.getConstructor().newInstance();
        } catch (Exception e) {
            logger.error("创建实例{}失败", targetClazz.getName(), e);
        }
        assert target != null;
        copy(source, target);
        return target;
    }

    public static <T1, T2> List<T2> copy(List<T1> source, Class<T2> targetClazz) {
        if (CollectionUtils.isEmpty(source)) {
            return Collections.emptyList();
        }
        List<T2> target = new ArrayList<>(source.size());
        for (T1 s : source) {
            target.add(copy(s, targetClazz));
        }
        return target;
    }

    private static BeanCopier getBeanCopier(Class<?> srcClazz, Class<?> desClazz) {
        String key = genKey(srcClazz, desClazz);
        BeanCopier copier;
        if (!BEAN_COPIER_CACHE.containsKey(key)) {
            copier = BeanCopier.create(srcClazz, desClazz, false);
            BEAN_COPIER_CACHE.put(key, copier);
        } else {
            copier = BEAN_COPIER_CACHE.get(key);
        }
        return copier;
    }

    private static String genKey(Class<?> srcClaszz, Class<?> desClazz) {
        return srcClaszz.getName() + desClazz.getName();
    }
}
